package com.ruoyi.project.erp.setupbill.controller;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.erp.saleservices.domain.Saleservices;
import com.ruoyi.project.erp.saleservices.service.ISaleservicesService;
import com.ruoyi.project.erp.setupbills.domain.Setupbills;
import com.ruoyi.project.erp.setupbills.service.ISetupbillsService;
import com.ruoyi.project.erp.so.domain.So;
import com.ruoyi.project.erp.sos.domain.Sos;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.erp.setupbill.domain.Setupbill;
import com.ruoyi.project.erp.setupbill.service.ISetupbillService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2020-08-31
 */
@Controller
@RequestMapping("/erp/setupbill")
public class SetupbillController extends BaseController
{
    private String prefix = "erp/setupbill";

    @Autowired
    private ISetupbillService setupbillService;
    @Autowired
    private ISetupbillsService setupbillsService;
    @Autowired
    private ISaleservicesService saleservicesService;

    @RequiresPermissions("erp:setupbill:view")
    @GetMapping()
    public String setupbill()
    {
        return prefix + "/setupbill";
    }


    /**
     * 手机端新增保存
     */
    @PostMapping("/addOrder")
    @ResponseBody
    public AjaxResult addOrder(Date ddate,String vin,String vinpic,String setuppic,String protectpic,String effectspic,String setupemp,String carstd, String emp, String ctype, String shop, String shopName, @RequestBody JSONObject json)
    {
        List<Setupbills> billsList = json.getJSONArray("billsList").toJavaList(Setupbills.class);
        Setupbill setupbill = new Setupbill();
        Long billId = Long.parseLong(RandomUtils.getNewRandomCode(6));
        String mcode = OddUtil.createOdd("",setupbillService.selectMaxCode());
        setupbill.setCode(mcode);
        setupbill.setDdate(ddate);
        setupbill.setEmp(emp);
        setupbill.setCtype(ctype);
        setupbill.setShop(shop);
        setupbill.setShopname(shopName);
        setupbill.setSt("保存");
        setupbill.setVin(vin);
        setupbill.setVinpic(vinpic);
        setupbill.setProtectpic(protectpic);
        setupbill.setEffectspic(effectspic);
        setupbill.setSetuppic(setuppic);
        setupbill.setSetupemp(setupemp);
        setupbill.setCarstd(carstd);

        int num = setupbillService.insertSetupbill(setupbill);
        String mid = setupbillService.selectMid();
        if(num>0){
            for(int i=0;i<billsList.size();i++){
                Setupbills temp = billsList.get(i);
                temp.setMid(Long.parseLong(mid));
                temp.setMcode(mcode);
                temp.setIsChangeDeal("否");
                temp.setIsChangeProduct("否");
                setupbillsService.insertSetupbills(temp);
            }
        }
        return toAjax(num);
    }

    /**
     * 手机端查询订单列表
     */
    @PostMapping("/listOrder")
    @ResponseBody
    public AjaxResult listOrder(@RequestBody Setupbill setupbill,String permit)
    {
        //查询当前用户的权限
       /* String[] emps = permit.split(",");
        List<Setupbill> resultList = new ArrayList<>();
        for(int i=0;i<emps.length;i++){
            setupbill.setEmp(emps[i]);
            resultList.addAll(setupbillService.selectSetupbillList(setupbill));
        }*/
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",setupbillService.selectSetupbillListPermit(setupbill,permit));
    }

    /**
     * 手机端获取token
     */
    @CrossOrigin
    @GetMapping("/getVinToken")
    @ResponseBody
    public AjaxResult getVinToken()
    {
        Map<String, String> param = new HashMap<String, String>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", "rMFBB4SMTFrF68LG2379Pu7G");
        param.put("client_secret", "1faSB4OqYc5Qx9XGbOdN57Vqw19bvI0p");
        String url="https://aip.baidubce.com/oauth/2.0/token";
        String str = HttpClientUtil.doGet(url,param);
        System.out.println("str---------------------------"+str);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200", str);
    }

    /**
     * 手机端获取vin
     */
    @PostMapping("/getVinCode")
    @ResponseBody
    public AjaxResult getVinCode(String accessToken,String filePath)
    {
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200", VinCode.vinCode(accessToken,"E:/ERP/soft/uploadPath2"+filePath.replaceAll("/profile","")));
    }

    /**
     * 手机端查询订单列表
     */
    @PostMapping("/listOrderQuery")
    @ResponseBody
    public AjaxResult listOrderQuery(@RequestBody Setupbill setupbill,String beginTime,String endTime,String permit)
    {
        //查询当前用户的权限
        /*String[] emps = permit.split(",");
        List<Setupbill> resultList = new ArrayList<>();
        for(int i=0;i<emps.length;i++){
            setupbill.setEmp(emps[i]);
            resultList.addAll(setupbillService.selectSetupbillListQuery(setupbill,beginTime,endTime));
        }*/
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",setupbillService.selectSetupbillListQuery(setupbill,beginTime,endTime,permit));
    }

    /**
     * 手机端根据订单ID查询订单详情
     */
    @PostMapping("/listOrderDetail")
    @ResponseBody
    public AjaxResult listOrderDetail(long orderId)
    {
        Setupbills setupbills = new Setupbills();
        setupbills.setMid(orderId);
        List<Setupbills> list = setupbillsService.selectSetupbillsList(setupbills);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",list);
    }

    /**
     * 手机端根据订单ID查询售后详情
     */
    @PostMapping("/listOrderDetailSale")
    @ResponseBody
    public AjaxResult listOrderDetailSale(long orderId)
    {
        Saleservices saleservices = new Saleservices();
        saleservices.setMid(orderId);
        List<Saleservices> list = saleservicesService.selectSaleservicesList(saleservices);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",list);
    }

    /**
     * 审批
     */
    @RequiresPermissions("erp:setupbill:edit")
    @PostMapping("/reviewSetupBill")
    @ResponseBody
    public AjaxResult reviewSetupBill(Long id)
    {
        //根据id获取施工单信息
        Setupbill setupbill = setupbillService.selectSetupbillById(id);
       /* //删除图片
        File file = new File("D:/ERP/soft/uploadPath2"+setupbill.getVinpic().replaceAll("/profile",""));
        file.delete();
        file = new File("D:/ERP/soft/uploadPath2"+setupbill.getSetuppic().replaceAll("/profile",""));
        file.delete();*/
        Setupbill temp =new Setupbill();
        temp.setCreditemp(getSysUser().getF102());
        temp.setCreditdt(new Date());
        temp.setId(id);
        temp.setSt("审核");
       /* //删除vin图片以及施工图片
        temp.setVinpic("");
        temp.setSetuppic("");*/
       return toAjax(setupbillService.reviewSetupbill(temp));
    }

    /**
     * 撤销审批
     */
    @RequiresPermissions("erp:setupbill:edit")
    @PostMapping("/reviewDisSetupBill")
    @ResponseBody
    public AjaxResult reviewDisSetupBill(Long id)
    {
        //根据id获取施工单信息
        Setupbill setupbill = setupbillService.selectSetupbillById(id);
        Setupbill temp =new Setupbill();
        temp.setCreditemp(null);
        temp.setCreditdt(null);
        temp.setId(id);
        temp.setSt("保存");
       return toAjax(setupbillService.reviewDisSetupbill(temp));
    }

    /**
     * PC查询子列表
     */
    @RequiresPermissions("erp:setupbill:list")
    @PostMapping("/listChild")
    @ResponseBody
    public TableDataInfo listChild(long mid)
    {
        Setupbills setupbills = new Setupbills();
        setupbills.setMid(mid);
        List<Setupbills> childList =setupbillsService.selectSetupbillsList(setupbills);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(childList);
        return rspData;
    }
    /**
         * PC查询售后记录
         */
        @RequiresPermissions("erp:setupbill:list")
        @PostMapping("/listSaleService")
        @ResponseBody
        public TableDataInfo listSaleService(long mid)
        {
            Saleservices saleservices = new Saleservices();
            saleservices.setMid(mid);
            List<Saleservices> childList =saleservicesService.selectSaleservicesList(saleservices);
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(0);
            rspData.setRows(childList);
            return rspData;
        }

    /**
     * PC查询销售产品
     */
    @RequiresPermissions("erp:setupbill:list")
    @PostMapping("/listSaleProduct")
    @ResponseBody
    public TableDataInfo listSaleProduct(Setupbills setupbills)
    {
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        List<Setupbills> list = setupbillsService.selectSetupbillsListLeft(setupbills);
        List<Setupbills> resultList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    /**
     * PC根据id获取订单
     */
    @RequiresPermissions("erp:so:list")
    @PostMapping("/getSetupBillById")
    @ResponseBody
    public AjaxResult getSetupBillById(long id)
    {
        Setupbill setupbill  = setupbillService.selectSetupbillById(id);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",setupbill);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("erp:setupbill:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Setupbill setupbill)
    {
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        List<Setupbill> list = setupbillService.selectSetupbillList(setupbill);
        List<Setupbill> resultList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("erp:setupbill:list")
    @PostMapping("/listBySale")
    @ResponseBody
    public TableDataInfo listBySale(Setupbill setupbill)
    {
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        List<Setupbill> list = setupbillService.selectSetupbillList(setupbill);
        List<Setupbill> resultList = new ArrayList<>();
        List<Setupbill> resultQueryList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            Setupbill temp = list.get(start);
            Saleservices saleservices = new Saleservices();
            saleservices.setMid(temp.getId());
            List<Saleservices> saleservicesList = saleservicesService.selectSaleservicesList(saleservices);
            temp.setSaleserviceTimes(saleservicesList.size());
            temp.setIsChangeDeal("否");
            temp.setIsChangeProduct("否");
            for(int i=0;i<saleservicesList.size();i++){
                if("换货".equals(saleservicesList.get(i).getCtype())){
                    temp.setIsChangeProduct("是");
                }
                if("未处理".equals(saleservicesList.get(i).getSt())){
                    temp.setIsChangeDeal("是");
                }
            }
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        if("是".equals(setupbill.getIsChangeDeal())){
            if("是".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("是".equals(resultList.get(m).getIsChangeDeal()) && "是".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else if("否".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("是".equals(resultList.get(m).getIsChangeDeal()) && "否".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else{
                for(int m=0;m<resultList.size();m++){
                    if("是".equals(resultList.get(m).getIsChangeDeal())){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }
            rspData.setRows(resultQueryList);
            rspData.setTotal(new PageInfo(list).getTotal());
            return rspData;
        }else if("否".equals(setupbill.getIsChangeDeal())){
            if("是".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("否".equals(resultList.get(m).getIsChangeDeal()) && "是".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else if("否".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("否".equals(resultList.get(m).getIsChangeDeal()) && "否".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else{
                for(int m=0;m<resultList.size();m++){
                    if("否".equals(resultList.get(m).getIsChangeDeal())){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }
            rspData.setRows(resultQueryList);
            rspData.setTotal(new PageInfo(list).getTotal());
            return rspData;
        }else{
            if("是".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("是".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else if("否".equals(setupbill.getIsChangeProduct())){
                for(int m=0;m<resultList.size();m++){
                    if("否".equals(resultList.get(m).getIsChangeProduct()) ){
                        resultQueryList.add(resultList.get(m));
                    }
                }
            }else{
                for(int m=0;m<resultList.size();m++){
                        resultQueryList.add(resultList.get(m));
                }
            }
            rspData.setRows(resultQueryList);
            rspData.setTotal(new PageInfo(list).getTotal());
            return rspData;
        }

       /* rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;*/
    }


    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("erp:setupbill:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Setupbill setupbill)
    {
        List<Setupbill> list = setupbillService.selectSetupbillList(setupbill);
        ExcelUtil<Setupbill> util = new ExcelUtil<Setupbill>(Setupbill.class);
        return util.exportExcel(list, "setupbill");
    }

    /**
     * 导出主子列表
     */
    @RequiresPermissions("erp:setupbill:export")
    @PostMapping("/exportAll")
    @ResponseBody
    public AjaxResult exportAll(Setupbill setupbill)
    {
        List<Setupbill> resultList = new ArrayList();
        List<Setupbill> list = setupbillService.selectSetupbillList(setupbill);
        for(int i=0;i<list.size();i++){
            Setupbills setupbills = new Setupbills();
            setupbills.setMid(list.get(i).getId());
            List<Setupbills> setupbillsList = setupbillsService.selectSetupbillsList(setupbills);
            for(int j=0;j<setupbillsList.size();j++){
                //Setupbill temp = list.get(i);
                Setupbill temp = new Setupbill();
                temp.setId(list.get(i).getId());
                temp.setSetuppic(list.get(i).getSetuppic());
                temp.setSt(list.get(i).getSt());
                temp.setVinpic(list.get(i).getVinpic());
                temp.setVin(list.get(i).getVin());
                temp.setCarstd(list.get(i).getCarstd());
                temp.setCode(list.get(i).getCode());
                temp.setSetupemp(list.get(i).getSetupemp());
                temp.setCreditdt(list.get(i).getCreditdt());
                temp.setCreditemp(list.get(i).getCreditemp());
                temp.setCtype(list.get(i).getCtype());
                temp.setDdate(list.get(i).getDdate());
                temp.setEmp(list.get(i).getEmp());
                temp.setShopname(list.get(i).getShopname());
                temp.setMemo(list.get(i).getMemo());
                temp.setMcode(setupbillsList.get(j).getMcode());
                if(setupbillsList.get(j).getSmemo() != null){
                    temp.setSmemo(setupbillsList.get(j).getSmemo());
                }
                temp.setPcode(setupbillsList.get(j).getPcode());
                temp.setPname(setupbillsList.get(j).getPname());
                temp.setPstd(setupbillsList.get(j).getPstd());
                temp.setPunit(setupbillsList.get(j).getPunit());
                temp.setQty(setupbillsList.get(j).getQty());
                resultList.add(temp);
            }
        }
        ExcelUtil<Setupbill> util = new ExcelUtil<Setupbill>(Setupbill.class);
        return util.exportExcel(resultList, "setupbill");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("erp:setupbill:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, Setupbill setupbill) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        setupbill.setSetuppic(fileName);
        return toAjax(setupbillService.insertSetupbill(setupbill));
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        System.out.println("filename+++++++"+fileName);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"00",fileName);
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Setupbill setupbill = setupbillService.selectSetupbillById(id);
        mmap.put("setupbill", setupbill);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    //@RequiresPermissions("erp:setupbill:edit")
    //@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Long id,String vin,String vinpic,String setuppic,String protectpic,String effectspic,String setupemp,String carstd, String ctype,@RequestBody JSONObject json)
    {
        List<Setupbills> billsList = json.getJSONArray("billsList").toJavaList(Setupbills.class);
        Setupbill setupbill = new Setupbill();
        setupbill.setId(id);
        setupbill.setCtype(ctype);
        setupbill.setSt("保存");
        setupbill.setVin(vin);
        setupbill.setVinpic(vinpic);
        setupbill.setProtectpic(protectpic);
        setupbill.setEffectspic(effectspic);
        setupbill.setSetuppic(setuppic);
        setupbill.setSetupemp(setupemp);
        setupbill.setCarstd(carstd);

        int num = setupbillService.updateSetupbill(setupbill);
        if(num>0){
            for(int i=0;i<billsList.size();i++){
                Setupbills temp = billsList.get(i);
                if(EmptyUtils.isNotEmpty(temp.getId())){
                    setupbillsService.updateSetupbills(temp);
                }else{
                    temp.setMid(id);
                    temp.setMcode(setupbillService.selectSetupbillById(id).getMcode());
                    setupbillsService.insertSetupbills(temp);
                }
            }
        }
        return toAjax(setupbillService.reviewSetupbill(setupbill));
    }

    @PostMapping("/editPC")
    @ResponseBody
    public AjaxResult editPC(Setupbill setupbill)
    {
        return toAjax(setupbillService.updateSetupbill(setupbill));
    }


    /**
     * 手机端删除删除
     */
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        Setupbill setupbill = setupbillService.selectSetupbillById(Long.parseLong(ids));
        if(!"保存".equals(setupbill.getSt())){
            return error("订单已审核，不能删除!");
        }
        return toAjax(setupbillService.deleteSetupbillByIds(ids));
    }
}
